<script lang="ts" setup>
import type { VxeGridPropTypes } from 'vxe-table';

import { reactive, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import {Apis} from '#/api';
import { useVxeTable } from '#/hooks/vxeTable';

const props = withDefaults(
  defineProps<{
    multiple?: boolean;
    showDepartment?: boolean;
  }>(),
  {
    multiple: false,
    showDepartment: true,
  },
);

const emit = defineEmits<{
  (e: 'confirm', row: any[]): any[];
  (e: 'rowClick', row: any): any;
}>();

const [messageApi] = message.useMessage();

const { xGridRef, triggerProxy, gridProps } = useVxeTable({ ref: 'xGridRef' });

const searchRef = ref();

const data = ref({
  title: '',
  limitMultipleNum: 10,
  userIds: [],
});
const treeData = ref([]);

const treeItemKey = ref([]);
const isEditMenu = ref(false);
const checkedId = ref(0);
const canMultiple = ref(false);
const limitMultipleNum = ref(10);
const checkRecords = ref<any>([]);

const searchBinding = ref({
  initialForm: {},
  columns: {
    name: {
      title: '用户姓名',
      key: 'name',
      component: {
        name: 'a-input',
        vModel: 'value',
        allowClear: true,
      },
      show: true,
    },
  },
  onSearch(_context: any) {
    triggerProxy('reload');
  },
});

function getColumns(_params: any = {}): VxeGridPropTypes.Columns {
  let columns: any[] = [{ type: 'seq', width: 50 }];
  if (props.multiple) {
    columns.push({ type: 'checkbox', title: '用户ID', width: 150 });
  }
  columns = [
    ...columns,
    { field: 'EMPLOYEE_NAME', title: '用户姓名', width: 120 },
    { field: 'EMPLOYEE_GENDER', title: '性别', width: 80 },
    { field: 'MAIL_ADDRESS', title: '邮箱', width: 150 },
    { field: 'PHONE_NUM', title: '联系方式', width: 120 },
    { field: 'ORG_NAME', title: '所属组织', minWidth: 120 },
  ];
  return columns;
}

/** Hooks - 表格 */
const gridOptions = reactive(
  gridProps({
    height: '400px',
    columns: getColumns(),
    pagerConfig: { size: 'mini' },
    proxyConfig: {
      autoLoad: true,
      ajax: {
        query: ({ page }) => {
          return Apis.api.core.orgemplbc.employee.post_paging({
            params: {
              page: page.currentPage,
              size: page.pageSize,
            },
            data: transferFormData(),
          });
        },
        querySuccess() {
          for (const row of checkRecords.value) {
            xGridRef.value!.setCheckboxRow(row, true);
          }
        },
      },
    },
    rowConfig: {
      keyField: 'ACCOUNT_ID',
    },
    checkboxConfig: {
      labelField: 'ACCOUNT_ID',
      // 取消显示全选头部按钮
      showHeader: false,
      highlight: true,
      range: false,
      // 保留勾选状态
      reserve: true,
      checkMethod: ({ row }) => {
        const checkRecordIds = checkRecords.value.map(
          (item) => item.ACCOUNT_ID,
        );
        if (
          checkRecords.value.length < limitMultipleNum.value ||
          checkRecordIds.includes(row.ACCOUNT_ID)
        ) {
          return true;
        }
        return false;
      },
    },
  }),
);

// 转换树行数据的方法
function transTree(list) {
  // 最终生成的树行结构
  const _treeData = [];

  // 对传入进来的 数据进行遍历，查找对应的子级
  list.forEach((item) => {
    // 给每一项添加子节点
    // item.children = []
    item.key = item.ORG_ID;
    item.title = item.ORG_NAME;
    // 如果 pid 为空，说明是最顶级，直接放到 _treeData 中即可
    if (item.ORG_LEVEL == 1) {
      _treeData.push(item);
    }

    // 根据前面的分析，pid 代表的是父级的 id，从而可以进行筛选子级
    // filter 方法会把满足条件到的每一项，组成一个数组进行返回
    const children = list.filter((data) => data.PARENT_ID === item.ORG_ID);

    // 如果没有子节点，直接 return 不做任何处理
    if (children.length === 0) return;

    // 将返回的子级进行赋值给父级(item)的 children 属性
    item.children = children;
  });

  // 将最终生成的数据返回出去
  return _treeData;
}

/** 拼接成用户中心期望的返回格式，吐槽xxxxxx */
function transferFormData() {
  let form = {
    subFilter: [] as any[],
  };

  const values = searchRef.value?.formData;

  if (values.name) {
    form.subFilter.push({
      symbol: 'like',
      singleValue: `%${values.name || ''}%`,
      key: 'EMPLOYEE_NAME',
    });
  }

  if (values.id) {
    form.subFilter.push({
      symbol: 'like',
      singleValue: `%${values.id || ''}%`,
      key: 'ACCOUNT_ID',
    });
  }

  if (form.subFilter.length === 2) {
    form.subFilter[1].logic = 'AND';
  }

  const newForm: any = {};

  if (treeItemKey.value && treeItemKey.value.length > 0) {
    newForm.subFilter = [
      {
        symbol: 'like',
        singleValue: treeItemKey.value[0],
        key: 'ORG_ID',
        logic: 'AND',
      },
    ];

    if (form.subFilter.length > 0) {
      newForm.subFilter.push({ subFilter: form.subFilter });
    }
    form = newForm;
  }

  return form;
}

async function loadDataByDept() {
  try {
    const data = await Apis.api.core.orgemplbc.organization.post_paging({
      params: { page: 1, size: 1000 },
      data: {
        subFilter: [
          {
            symbol: 'like',
            singleValue: '0001%',
            key: 'ORG_ID',
            logic: 'AND',
          },
        ],
      },
    });
    treeData.value = transTree(data.rows);
  } catch (error) {
    logger.error('loadDataByDept error', error);
  }
}

/**
 * 单元行点击事件
 */
function handleCellClick({ row }) {
  emit('rowClick', {
    ...row,
    label: row.EMPLOYEE_NAME,
    value: row.ACCOUNT_ID,
    mobile: row.PHONE_NUM,
  });
}

const currTypeData = ref<any>({});

const treeItemTitle = ref('');

function handleTreeSelectChange(keys) {
  if (keys.length > 0) {
    const treeItem = keys[0];
    treeItemKey.value = keys;
    treeItemTitle.value = treeItem.label;
    // searchParams.type = treeItem.key;
    Object.assign(currTypeData.value, treeItem);
    isEditMenu.value = true;
    checkedId.value = treeItem.id;
    triggerProxy('reload');
  } else {
    currTypeData.value = {};
    checkedId.value = 0;
    isEditMenu.value = false;
    treeItemKey.value = [];
    treeItemTitle.value = '';
    // searchParams.type = undefined;
    triggerProxy('reload');
  }
}
/**
 * 复选框选中事件
 * @param e
 */
function handleCheckboxChange(e) {
  const currRows = xGridRef.value?.getCheckboxRecords() || [];
  const otherRows = xGridRef.value?.getCheckboxReserveRecords() || [];
  const allRows = [...currRows, ...otherRows];

  if (e.checked) {
    const existingIds = new Set(
      checkRecords.value.map((item) => item.ACCOUNT_ID),
    );

    if (!existingIds.has(e.row.ACCOUNT_ID)) {
      checkRecords.value = [...checkRecords.value, e.row];
    }
  } else {
    handleCloseTag(e.row);
  }

  console.log('[ checkRecords.value ] >', checkRecords.value);
  if (allRows.length >= limitMultipleNum.value) {
    messageApi.warning(`最多只能选择${limitMultipleNum.value}条数据`);
  }
}

function handleCloseTag(row) {
  checkRecords.value = checkRecords.value.filter(
    (item) => item.ACCOUNT_ID != row.ACCOUNT_ID,
  );
  xGridRef.value?.setCheckboxRow(row, false);
}

const title = ref('选择人员');

const [Modal, modalApi] = useVbenModal({
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      data.value = modalApi.getData<Record<string, any>>() || {};
      if (data.value.title) {
        title.value = data.value.title;
      }
      // canMultiple.value = data.value.multiple || false;
      if (data.value.limitMultipleNum) {
        limitMultipleNum.value = data.value.limitMultipleNum;
      }
      console.log(data.value.userIds);
      const rows: any = [];
      for (const element of checkRecords.value) {
        if (data.value.userIds || [].includes(element.ACCOUNT_ID)) {
          rows.push(element);
        }
      }
      checkRecords.value = rows;
      //
      loadDataByDept();
    }
  },
  onConfirm() {
    emit('confirm', checkRecords.value);
    modalApi.close();
  },
  onCancel() {
    modalApi.close();
  },
});
</script>
<template>
  <Modal :title="title">
    <div v-if="props.multiple || canMultiple" class="py-12px flex flex-row">
      <span class="mr-12px block">已选择：</span>
      <div class="flex flex-1 flex-row">
        <a-space>
          <a-tag
            v-for="(item, index) in checkRecords"
            :key="index"
            closable
            @close="handleCloseTag(item)"
          >
            {{ item.EMPLOYEE_NAME }}-{{ item.ACCOUNT_ID }}
          </a-tag>
        </a-space>
      </div>
    </div>
    <a-row class="h-full">
      <a-col :span="5" class="">
        <a-tree
          :tree-data="treeData"
          auto-expand-parent
          block-node
          class="draggable-tree"
          @select="handleTreeSelectChange"
        />
      </a-col>
      <a-col :span="19" class="flex flex-col">
        <fs-search ref="searchRef" v-bind="searchBinding" />
        <div class="min-h-300px flex-1">
          <VxeGrid
            ref="xGridRef"
            class="h-420px"
            v-bind="gridOptions"
            @cell-click="handleCellClick"
            @checkbox-change="handleCheckboxChange"
          />
        </div>
      </a-col>
    </a-row>
  </Modal>
</template>
